package com.engine.modules.vector.controller;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.baseEntity.jsonResponse.JsonResponseEntity;
import com.engine.common.constant.CommonConstant;
import com.engine.common.exception.InvalidTokenRuntimeException;
import com.engine.common.util.ListMapAndJson;
import com.engine.common.util.TokenVerifyUtil.AuthRedisUtil;
import com.engine.common.util.TokenVerifyUtil.TokenVerifyUtil;
import com.engine.modules.vector.mapper.VectorSourceMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "2-矢量数据操作接口")
@ApiSort(value = 2)
@CrossOrigin
@RequestMapping("/Vector/Source")
@Slf4j
public class VectorSourceController {

    @Autowired
    AuthRedisUtil authRedisUtil;
    @Autowired
    VectorSourceMapper vectorSourceMapper;


    @ApiOperation(value = "获取geojson，通过坐标", notes = "通过minx,miny,maxx,maxy组成矩形，获取矩形内的矢量数据，返回geojson")
    @GetMapping(value = "/selectGeojsonByXY/{tableName}/{token}")
    @ApiOperationSupport(order = 1)
    public String selectGeojsonByXY(@PathVariable("tableName") String tableName,
                                    @RequestParam(value = "minx") double minx,
                                    @RequestParam(value = "miny") double miny,
                                    @RequestParam(value = "maxx") double maxx,
                                    @RequestParam(value = "maxy") double maxy,
                                    @PathVariable("token") String token,
                                    HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<Map<String, Object>> rsList = vectorSourceMapper.selectGeojsonByXY(minx, miny, maxx, maxy, tableName, access);
            return ListMapAndJson.ListMap2Geojson(rsList);
        } catch (InvalidTokenRuntimeException e)
        {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }

    @ApiOperation(value = "获取geojson，通过ids", notes = "通过ids(id数组)，获取矢量数据，返回geojson")
    @ApiOperationSupport(order = 2)
    @GetMapping(value = "/selectGeojsonByIds/{tableName}/{token}")
    @ResponseBody
    public String selectGeojsonByIds(@PathVariable("tableName") String tableName,
                                     @RequestParam(value = "ids") List<String> ids,
                                     @PathVariable("token") String token,
                                     HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<Map<String, Object>> rsList = vectorSourceMapper.selectGeojsonByIds(ids, tableName, access);
            return ListMapAndJson.ListMap2Geojson(rsList);
        } catch (InvalidTokenRuntimeException e)
        {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }

    @ApiOperation(value = "获取geojson，通过geometry", notes = "通过Geometry（此Geometry是geojson中的数据格式），获取数据，返回geojson")
    @PostMapping(value = "/selectGeojsonByGeometry/{tableName}/{token}", produces = "application/json;charset=UTF-8")
    @ApiOperationSupport(order = 3)
    @ResponseBody
    public String selectGeojsonByGeometry(@PathVariable("tableName") String tableName,
                                          @RequestBody String geometry,
                                          @PathVariable("token") String token,
                                          HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<Map<String, Object>> rsList = vectorSourceMapper.selectGeojsonByGeometry(geometry, tableName, access);
            return ListMapAndJson.ListMap2Geojson(rsList);
        } catch (InvalidTokenRuntimeException e)
        {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }

//    @ApiOperation(value = "获取geojson，通过where子句", notes = "通过where子句，获取矢量数据，返回geojson，whereSql不能为空，若要为空请用TRUE填充")
//    @GetMapping(value = "/selectGeojsonByWhereSQL/{tableName}/{token}")
//    @ApiOperationSupport(order = 5)
//    @ResponseBody
//    public String selectGeojsonByWhereSQL(@PathVariable("tableName") String tableName,
//                                          @RequestParam(value = "whereSql") String whereSql,
//                                          @PathVariable("token") String token,
//                                          HttpServletResponse response) {
//        try {
//            String access = TokenVerify.tokenVerifyGetAuthCo(token);
//            List<Map<String, Object>> rsList = vectorSourceMapper.selectGeojsonByWhereSQL(whereSql, tableName, access);
//            return ListMapAndJson.ListMap2Geojson(rsList);
//        } catch (InvalidTokenRuntimeException e)
//        {
//            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
//                    response);
//            return jsonResponseEntity.getJsonString();
//        }
//        catch (Exception e) {
//            log.error(e.getMessage(), e);
//            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
//            return jsonResponseEntity.getJsonString();
//        }
//    }

    @ApiOperation(value = "插入矢量，通过geojson", notes = "通过geojson插入数据，会根据features的内容插入多条数据，会自动生成id（geojson中的id无效），返回成功插入数据的uuid")
    @PostMapping(value = "/insertByGeojson/{tableName}/{token}", produces = "text/html;charset=UTF-8")
    @ApiOperationSupport(order = 8)
    @ResponseBody
    public String insertByGeojson(@PathVariable("tableName") String tableName,
                                  @RequestBody String geoJson,
                                  @PathVariable("token") String token,
                                  HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<String> uuids = vectorSourceMapper.insertByGeojson(geoJson, tableName);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, JSONObject.toJSONString(uuids), response);
            return jsonResponseEntity.getJsonString();
        } catch (InvalidTokenRuntimeException e) {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }
    @ApiOperation(value = "插入矢量，通过geojson,Id为UseOwnId", notes = "通过geojson插入数据，会根据features的内容插入多条数据，会自动生成id（geojson中的id无效），返回成功插入数据的uuid")
    @PostMapping(value = "/insertByGeojsonUseOwnId/{tableName}/{token}", produces = "text/html;charset=UTF-8")
    @ApiOperationSupport(order = 8)
    @ResponseBody
    public String insertByGeojsonUseOwnId(@PathVariable("tableName") String tableName,
                                  @RequestBody String geoJson,
                                  @PathVariable("token") String token,
                                  HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<String> uuids = vectorSourceMapper.insertByGeojsonUseOwnId(geoJson, tableName);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, JSONObject.toJSONString(uuids), response);
            return jsonResponseEntity.getJsonString();
        } catch (InvalidTokenRuntimeException e) {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }

    @ApiOperation(value = "插入矢量(转换字段格式)，通过geojson", notes = "通过geojson插入数据，会转化geojson的数字字段和字符字段，返回成功插入数据的uuid")
    @PostMapping(value = "/insertByGeojsonJudgeByAccessChangeStr/{tableName}/{token}", produces = "text/html;charset=UTF-8")
    @ApiOperationSupport(order = 9)
    @ResponseBody
    public String insertByGeojsonJudgeByAccessChangeStr(@PathVariable("tableName") String tableName,
                                                        @PathVariable("token") String token,
                                                        @RequestParam(value = "intCloumns", defaultValue = "", required = false) String intCloumns,
                                                        @RequestParam(value = "floatCloumns", defaultValue = "", required = false) String floatCloumns,
                                                        @RequestBody String geoJson,
                                                        HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            if ((!intCloumns.equals("")) || (!floatCloumns.equals("")))
                geoJson = ListMapAndJson.GeojsonChangeNumColumns(geoJson, intCloumns, floatCloumns);
            List<String> uuids = vectorSourceMapper.insertByGeojson(geoJson, tableName);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, JSONObject.toJSONString(uuids), response);
            return jsonResponseEntity.getJsonString();
        } catch (InvalidTokenRuntimeException e) {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }


    @ApiOperation(value = "更新矢量，通过geojson", notes = "通过geojson更新数据，会根据features的内容更新多条数据，会基于id进行匹配，返回成功更新多少数据")
    @PostMapping(value = "/updateByGeojson/{tableName}/{token}", produces = "text/html;charset=UTF-8")
    @ApiOperationSupport(order = 10)
    @ResponseBody
    public String updateByGeojson(@PathVariable("tableName") String tableName,
                                  @RequestBody String geoJson,
                                  @PathVariable("token") String token,
                                  HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<String> uuid = vectorSourceMapper.updateByGeojson(geoJson, tableName, access);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, "更新成功,更新：" + uuid.size() + "条", response);
            return jsonResponseEntity.getJsonString();
        } catch (InvalidTokenRuntimeException e)
        {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }

    @ApiOperation(value = "更新矢量(转换数据)，通过geojson", notes = "通过geojson更新数据，会根据features的内容更新多条数据，会基于id进行匹配，返回成功更新多少数据，可将字符串转数值")
    @PostMapping(value = "/updateByGeojsonChangeStr/{tableName}/{token}", produces = "text/html;charset=UTF-8")
    @ApiOperationSupport(order = 11)
    @ResponseBody
    public String updateByGeojsonChangeStr(@PathVariable("tableName") String tableName,
                                           @RequestBody String geoJson,
                                           @RequestParam(value = "intCloumns", defaultValue = "", required = false) String intCloumns,
                                           @RequestParam(value = "floatCloumns", defaultValue = "", required = false) String floatCloumns,
                                           @PathVariable("token") String token,
                                           HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            if ((!intCloumns.equals("")) || (!floatCloumns.equals("")))
                geoJson = ListMapAndJson.GeojsonChangeNumColumns(geoJson, intCloumns, floatCloumns);
            List<String> uuid = vectorSourceMapper.updateByGeojson(geoJson, tableName, access);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, "更新成功,更新：" + uuid.size() + "条", response);
            return jsonResponseEntity.getJsonString();
        } catch (InvalidTokenRuntimeException e)
        {
            return null;
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @ApiOperation(value = "删除矢量，通过geojson", notes = "通过geojson逻辑删除数据（def_flag置1），仅会匹配geojson中每个feature下的properties.id字段，其他数据无效，返回成功删除多少数据")
    @PostMapping(value = "/deleteByGeojson/{tableName}/{token}", produces = "text/html;charset=UTF-8")
    @ApiOperationSupport(order = 12)
    @ResponseBody
    public String deleteByGeojson(@PathVariable("tableName") String tableName,
                                  @RequestBody String geoJson,
                                  @PathVariable("token") String token,
                                  HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            Integer i = vectorSourceMapper.deleteLogicByGeojson(geoJson, tableName, access);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, "删除成功,删除：" + i + "条", response);
            return jsonResponseEntity.getJsonString();
        } catch (InvalidTokenRuntimeException e)
        {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }


    @ApiOperation(value = "删除矢量，通过ids", notes = "通过ids逻辑删除数据（def_flag置1）")
    @GetMapping(value = "/deleteByIds/{tableName}/{token}")
    @ApiOperationSupport(order = 13)
    @ResponseBody
    public String deleteByIds(@PathVariable("tableName") String tableName,
                              @RequestParam(value = "ids") List<String> ids,
                              @PathVariable("token") String token,
                              HttpServletResponse response) {
        try {
            String access = TokenVerifyUtil.tokenVerify(token);
            List<String> list= vectorSourceMapper.deleteLogicByIds(ids, tableName, access);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(true, CommonConstant.SC_OK_200, "删除成功,删除：" + list.size() + "条", response);
            return jsonResponseEntity.getJsonString();

        } catch (InvalidTokenRuntimeException e)
        {
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "token错误，e：" + e.getMessage(),
                    response);
            return jsonResponseEntity.getJsonString();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResponseEntity jsonResponseEntity = new JsonResponseEntity(false, CommonConstant.SC_BK_ERROR, "查询出错，e：" + e.getMessage(), response);
            return jsonResponseEntity.getJsonString();
        }
    }
}
